package com.qyer.commons.utils;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.Iterator;
import java.util.List;

/**
 * User: Z J Wu Date: 2016/05/31 Time: 14:15 Package: com.qyer.commons.utils
 */
public class GenericStringUtils {

  public static <E> String iterable2String(Iterable<E> iterable, String separator, String leftQuote,
                                           String rightQuote) {
    if (iterable == null) {
      return null;
    }
    StringBuilder sb = new StringBuilder();

    Iterator<E> it = iterable.iterator();
    if (!it.hasNext()) {
      sb.append(leftQuote);
      sb.append(rightQuote);
      return sb.toString();
    }
    sb.append(leftQuote);
    for (; ; ) {
      E e = it.next();
      sb.append(e == iterable ? "(Same Iterable)" : e);
      if (!it.hasNext()) {
        return sb.append(rightQuote).toString();
      }
      sb.append(separator);
    }
  }

  public static String repeatWithLeftRightQuote(int repeatCount, String repeatString,
                                                String separator, String leftQuote,
                                                String rightQuote) {
    StringBuilder sb = new StringBuilder();
    if (repeatCount <= 0) {
      sb.append(leftQuote);
      sb.append(rightQuote);
      return sb.toString();
    }
    sb.append(leftQuote);
    sb.append(repeatString);
    for (int i = 1; i < repeatCount; i++) {
      sb.append(separator);
      sb.append(repeatString);
    }
    sb.append(rightQuote);
    return sb.toString();
  }

  public static void main(String[] args) {
    List<String> list = Lists.newArrayListWithCapacity(5);
    for (int i = 0; i < 5; i++) {
      list.add(RandomStringUtils.randomAlphabetic(10));
    }
    System.out.println(iterable2String(list, ", ", "( ", " )"));
    System.out.println(repeatWithLeftRightQuote(-1, "?", ",", "(", ")"));
  }
}
